import { CurrentUser } from '@/models/user';

interface ExtendsUser extends CurrentUser {
  accessToken?: string;
  userCode?: string;
  corpId?: string;
  [key: string]: any;
}

// bill 里面需要用作初始化的属性
const BILL_REG = [
  'name',
  'username',
  'userCode',
  'companyCode',
  'companyCodeName',
  'deptCode',
  'deptName',
];

export const setUserInfo: (userObject: Partial<ExtendsUser>) => boolean = (
  userObject: Partial<ExtendsUser>,
) => {
  try {
    const bill: any = {};
    for (const item of BILL_REG) {
      // todo 用来兼容公司部门确实问题
      switch (item) {
        // case 'companyCode':
        //   bill[item] = userObject[item] || 'ORG_FSSC';
        //   break;
        // case 'deptCode':
        //   bill[item] = userObject[item] || 'DEPARTMENT2106241';
        //   break;
        default:
          bill[item] = userObject[item];
          break;
      }
    }
    userObject.bill = bill;
    localStorage.setItem('currentUser', JSON.stringify(userObject));
    return true;
  } catch (e) {
    console.warn('设置本地用户信息出错');
    return false;
  }
};

export const getUserInfo: () => Partial<ExtendsUser> = () => {
  try {
    const currentUserString: string | null = localStorage.getItem('currentUser') || '{}';
    const currentUser: Partial<ExtendsUser> = JSON.parse(currentUserString as string);
    return currentUser || {};
  } catch (e) {
    console.warn('解析本地用户信息出错');
    return {};
  }
};

export const getUserInfoByKey = (key: string) => {
  const currentUser: Partial<ExtendsUser> = getUserInfo();
  console.log('currentUser', currentUser);
  return currentUser[key];
};

export const getAccessToken = () => {
  return getUserInfoByKey('accessToken');
};

export const getRoles = () => {
  return getUserInfoByKey('roleIdList') || [];
};

export const getDataAuths = () => {
  return getUserInfoByKey('dataAuths') || [];
};
